package com.turing.data.scripts.xgpsgg.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.turing.common.util.FileUtils
import com.turing.common.util.Log
import com.turing.common.util.StringUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO


class SecuritiesAccount_12351_r15_filter {

    public static void main(String[] args) {
        DependParamsVO param = new DependParamsVO()
        param.setJSONPathMap(new LinkedHashMap<String, String>())
//        param.getJSONPathMap().put("abc", "http://media.tlrobot.com/group1/M00/0C/29/rBIHD2CjdRiAPV_eAACdNH_q44831.json")
//        param.getJSONPathMap().put("abc", "/Users/luoshiwei/Desktop/tmp/ex/extractor/e675314b-1c3b-4bb7-9a9f-ef5c268b7b6d/688316_20210305_1/json/688316_20210305_1_converted.json")
        param.getJSONPathMap().put("abc", "F:\\Answer\\688316_20210305_1_47_converted.json")
        List<TaskElementVO.DrawResultVO> s = doConvert(param)
        for (int z = 0; z < s.size(); z++) {
            def get = s.get(z)
            println(get.text)
        }
    }

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams) {
//        def REGEX_COMPANY_1 = /.*银华.*/
//        def REGEX_COMPANY_1 = /.*/
        String SEARCH_TITLE = "证券账户"

        String[] Search_Titles = ["配售对象编码", "配售对象代码", "证券账户号", "证券账户", "证券账号", "配售对象"]
        Date begin = new Date()
        Date end = new Date()

        List<String> titleList = new LinkedList<>()
        Map<String, String> oldAndNewTitleMap = new HashMap<>()
        Map<String, String> titleAndValueMap = new HashMap<>()
//        Map<String, List<String>> DictionArtesMap = dependParams.getDictionArtes();
//        List<String> dictionArtes = DictionArtesMap.get("证券账户")

        List<String> keys = dependParams.getJSONPathMap().keySet() as List<String>
        List<TaskElementVO.DrawResultVO> finalResults = new ArrayList<>()

        for (int z = 0; z < keys.size(); z++) {
            String path = dependParams.getJSONPathMap().get(keys.get(z))
            String format_json_path = "/Users/luoshiwei/Desktop/response.json"

            if (!StringUtils.isEmpty(path)) {
                format_json_path = path
            }

            begin = new Date()
            String jsonString = FileUtils.loadJson(format_json_path)

            List<String> newTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            List<String> oldTitleList = ["序号", "投资者名称", "配售对象名称", "证券账户", "申购数量（万股）",
                                         "初步配售数量（股）", "获配金额（元）",
                                         "经纪佣金（元）", "合计应缴（元）", "分类"]
            end = new Date()
            println "load json: " + (end.getTime() - begin.getTime()) / 1000 / 1000


            //标题映射
            for (int i = 0; i < newTitleList.size(); i++) {
                String newTitle = newTitleList[i]
                String oldTitle = oldTitleList[i]
                oldAndNewTitleMap.put(oldTitle, newTitle)
            }


            boolean foundTitle = false

            begin = new Date()
            JSONArray formatArr = JSONArray.parse(jsonString)
            end = new Date()
            println "parse json array: " + (end.getTime() - begin.getTime()) / 1000 / 1000

            begin = new Date()
            println begin


            for (int pageNo = 0; pageNo < formatArr.size(); pageNo++) {
                JSONObject pageObj = formatArr.getJSONObject(pageNo)
                JSONArray paraArr = pageObj.getJSONArray("paragraphs")
                for (int paragraphsNo = 0; paragraphsNo < paraArr.size(); paragraphsNo++) {

                    JSONObject paraObj = paraArr.getJSONObject(paragraphsNo)
                    JSONArray lineArr = paraObj.getJSONArray("lines")

                    //每一行
                    for (int line = 0; line < lineArr.size(); line++) {
                        titleAndValueMap = new HashMap<>()
                        JSONObject lineObj = lineArr.getJSONObject(line)
                        String lineId = lineObj.getString("lineId")
                        if (JSON.isValidArray(lineObj.getString("cells"))) {
                            JSONArray objContentArr = lineObj.getJSONArray("cells")
                            if (!StringUtils.isEmpty(objContentArr)) {

                                if (!foundTitle && objContentArr.size()>6) {
                                    int foundTitleNum = 0
                                    //寻找表头
                                    for (int i = 0; i < objContentArr.size(); i++) {
                                        JSONObject objContentObj = objContentArr.getJSONObject(i)
                                        String objContentString = objContentObj.getString("objContent")
                                        if (objContentString.contains("\r")) {
                                            objContentString = objContentString.replace("\r", "")
                                        }
                                        //标题栏
                                        if (oldTitleList.contains(objContentString)
                                                || newTitleList.contains(objContentString)
                                                || arrContains(Search_Titles, objContentString)) {
                                            foundTitleNum++

                                        }

                                        String title = oldAndNewTitleMap.get(objContentString)
                                        if (!StringUtils.isEmpty(title)) {
                                            titleList.add(title)
                                        } else if (arrContains(Search_Titles, objContentString)) {
                                            titleList.add(SEARCH_TITLE)
                                        } else {
                                            titleList.add(objContentString)
                                        }

                                    }
                                    if (foundTitleNum >= 3) {
                                        foundTitle = true
                                    } else {
                                        titleList = new LinkedList<>()
                                    }

                                } else {
                                    def wordCount = 0
                                    //每一列
                                    for (int column = 0; column < objContentArr.size(); column++) {
                                        JSONObject objContentObj = objContentArr.getJSONObject(column)
                                        String objContentString = objContentObj.getString("objContent")
                                        def cWordCount = objContentString.length()
                                        if (objContentString.contains("\r")) {
                                            objContentString = objContentString.replace("\r", "")
                                        }

                                        //具体数值栏
                                        if (foundTitle) {
                                            String title = titleList[column]
                                            if (title != null && !StringUtils.isEmpty(title)) {
                                                titleAndValueMap.put(title, objContentString)
                                            }
                                            String businessValue = titleAndValueMap.get(SEARCH_TITLE)
                                            try{
                                                if (!StringUtils.isEmpty(businessValue) && (title != null &&
                                                        (title.contains(SEARCH_TITLE) || Search_Titles.contains(title)))) {
                                                    if (!StringUtils.isEmpty(businessValue) && (title != null &&
                                                            (title.contains(SEARCH_TITLE) || Search_Titles.contains(title)))) {
                                                        TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
                                                        drawResultVO.setBusinessValue(objContentString)
                                                        drawResultVO.setText(objContentString)
                                                        drawResultVO.setPara_info([lineId])
                                                        drawResultVO.setPos_info([wordCount, cWordCount + wordCount])
                                                        drawResultVO.setPage(lineId.split("_")[1] as Integer)
                                                        drawResultVO.setChildTaskSn(keys.get(z))
                                                        drawResultVO.setType(1)
                                                        if(!Search_Titles.contains(objContentString)){
                                                            finalResults.add(drawResultVO)
                                                        }
                                                    }
                                                }
                                            }catch (Exception e){
                                                Log.error(">>>>>>>>>>>>>>e",e)
                                            }

                                        }
                                        wordCount += cWordCount
                                    }
                                }
                            }
                        }
                    }
                }
            }



            end = new Date()
            println end
            println "ex elements: " + (end.getTime() - begin.getTime()) / 1000 / 1000
        }

        Log.info(">>>>>>>>>>>>>>>>>证券账户的结果对象有"+finalResults.size()+"个")
        try{
            if (finalResults.size() == 0) {
                Map<String, List<TaskElementVO.DrawResultVO>> relatedMap = dependParams.relatedBusiElements
                List<TaskElementVO.DrawResultVO> AllotmentAmountMap = relatedMap.get("投资者名称")
                Log.info(">>>>>>>>>>>>>>>>>证券账户关联的投资者名称对象数量"+AllotmentAmountMap.size()+"个")
                if (AllotmentAmountMap.size() > 0) {
                    for (int i = 0; i < AllotmentAmountMap.size(); i++) {
                        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                        defaultDrawResultVO.setText("")
                        defaultDrawResultVO.setBusinessValue("")
                        defaultDrawResultVO.setStart(0)
                        defaultDrawResultVO.setEnd(1)
                        defaultDrawResultVO.setDegree("0")
                        defaultDrawResultVO.setEndLineNo(0)
                        defaultDrawResultVO.setPara_info([])
                        defaultDrawResultVO.setPos([])
                        defaultDrawResultVO.setPos_info([0,1])
                        defaultDrawResultVO.setStartLineNo(0)
                        defaultDrawResultVO.setSequence(UUID.randomUUID().toString())
                        defaultDrawResultVO.setFirstSequence(1)
                        defaultDrawResultVO.setSubProductId(0)
                        defaultDrawResultVO.setNextSequence("")
                        defaultDrawResultVO.setType(1)
                        defaultDrawResultVO.setChildTaskSn("")

                        finalResults.add(defaultDrawResultVO)
                    }
                }else {
                    TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                    defaultDrawResultVO.text = ""
                    finalResults.add(defaultDrawResultVO)
                }
            }
        }catch(Exception e){
            Log.error(">>>>>>>>>>>>>e"+e)
//            e.printStackTrace()
        }

        Log.info(">>>>>>>>>>>>>>>>>最终返回的证券账户的对象"+finalResults.size()+"个")
        return finalResults
    }

    static boolean arrContains(String[] Search_Titles, String objContentString) {
        if (Search_Titles.contains(objContentString)) {
            return true
        }
        for (i in 0..<Search_Titles.length) {
            String title = Search_Titles[i]
            title = title.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            String anoContentString = objContentString.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            if (title == anoContentString || anoContentString.contains(title)) {
                if (title == "配售对象" && anoContentString != "配售对象") {
                    continue
                }
                return true
            }
        }

        return false
    }
}

